import sys
import threading
from PyQt5.QtWidgets import (
    QApplication,
    QWidget,
    QPushButton,
    QLabel,
    QLineEdit,
    QComboBox,
    QCheckBox,
)
import datetime
import time
import serial_lib
import serial
import serial.tools.list_ports

g_flag_quit = False


def set_flag_quit(state):
    global g_flag_quit
    g_flag_quit = state


def btn0_clicked():
    print("#button_0 clicked!")
    print("list index=", combox.currentIndex())
    print("list text=", combox.currentText())
    print("checkbox state=", checkbox.isChecked())


def btn1_clicked():
    serial_lib.uart_send("334455667788")
    serial_lib.net_send("11223344445566")
    print("#button_1 clicked!")

    w.setStyleSheet("background-color:red;")
    print("Account=>", edit1.text())
    checkbox.setChecked(True)


def btn2_clicked():
    print("#button_2 clicked!")
    w.setStyleSheet("background-color:yellow;")
    print("Password=>", edit2.text())
    checkbox.setChecked(False)


def init_ui():
    global w, btn0, btn1, btn2, combox, edit1, edit2, checkbox
    w = QWidget()
    w.resize(300, 200)


def loop_run(*arg):
    # global g_flag_quit
    time.sleep(0.5)
    print("start loop_run...", g_flag_quit)
    cnt = 0
    while True:
        if g_flag_quit == True:
            break

        dat = serial_lib.get_uart_rb()
        if dat != None:
            print("get_uart:", hex(dat))  ##在界面处理收到电控板-->TFT的串口数据
            cnt += 1
            if cnt > 100:
                time.sleep(0.05)
                cnt = 0
        else:
            time.sleep(0.25)
            cnt = 0
    print("end loop_run...")
    sys.exit(0)
    return


def list_ports(combox):
    combox.clear()
    ports = serial.tools.list_ports.comports()
    for port, desc, hwid in sorted(ports):
        print(f"{port}: {desc} ({hwid})")
        combox.addItem(port)


g_init_serv_flag = False


def btn_start_clicked():
    global g_init_serv_flag
    if g_init_serv_flag == False:
        serial_lib.set_net_info(edit_serv_ip.text(), edit_serv_port.text())
        serial_lib.start_net_to_uart()
        g_init_serv_flag = True
    return


if __name__ == "__main__":
    # 创建QApplication类的实例，并传入命令行参数
    app = QApplication(sys.argv)
    # 创建QWidget类的实例，相当于创建一个窗口
    w = QWidget()
    # 调整窗口的大小（宽，高）
    w.resize(800, 600)
    # 设置widget窗口背景颜色
    w.setStyleSheet("background-color:#e5ffe5;")

    # td1 = threading.Thread(target=loop_run, args=(1,))
    # td1.start()

    txt1 = QLabel(w)
    txt1.setText("ServIP:")
    txt1.move(5, 8)

    txt2 = QLabel(w)
    txt2.setText("<---->Uart:")
    txt2.move(230, 8)

    edit_serv_ip = QLineEdit(w)
    edit_serv_ip.move(50, 5)

    edit_serv_port = QLineEdit(w)
    edit_serv_port.move(190, 5)
    edit_serv_port.resize(40, 20)

    combox_uart = QComboBox(w)
    combox_uart.move(310, 5)
    list_ports(combox_uart)

    btn_start = QPushButton("SATRT", w)
    btn_start.move(380, 5)
    btn_start.clicked.connect(btn_start_clicked)

    # 显示窗口
    w.show()
    # 进入循环的主循环，并通过exit函数确保主循环安全结束
    ret = app.exec_()
    sys.exit(ret)


#####################################################

if __name__ == "__main__77":
    # 创建QApplication类的实例，并传入命令行参数
    app = QApplication(sys.argv)
    # 创建QWidget类的实例，相当于创建一个窗口
    w = QWidget()
    # 调整窗口的大小（宽，高）
    w.resize(320, 240)
    # 设置widget窗口背景颜色
    w.setStyleSheet("background-color:#00ee66;")

    current_time = datetime.datetime.now()
    print("start main test,current_time:", str(current_time))

    # 设置窗口位置
    w.move(100, 200)
    # 设置窗口的标题
    w.setWindowTitle("pyqt5 title")
    # 创建按键
    btn0 = QPushButton("OK", w)
    btn0.move(80, 0)
    btn0.clicked.connect(btn0_clicked)

    btn1 = QPushButton("Fist_Button", w)
    btn1.setToolTip("this Btn1 tips")  # button tips text
    btn1.move(20, 50)
    btn1.clicked.connect(btn1_clicked)

    btn2 = QPushButton("Second_Button", w)
    btn2.setToolTip("this Btn2 tips")  # button tips text
    btn2.move(120, 50)
    btn2.clicked.connect(btn2_clicked)

    edit1 = QLineEdit(w)
    edit1.setPlaceholderText("Account:")
    edit1.move(20, 100)

    edit2 = QLineEdit(w)
    edit2.setPlaceholderText("Password:")
    edit2.move(20, 130)
    edit2.setEchoMode(QLineEdit.Password)

    combox = QComboBox(w)
    combox.addItem("Item0")
    combox.addItem("Item1")
    combox.addItem("Item2")
    combox.move(20, 0)

    checkbox = QCheckBox(w)

    serial_lib.start_net_to_uart()
    td1 = threading.Thread(target=loop_run, args=(1,))
    td1.start()

    # 显示窗口
    w.show()
    # 进入循环的主循环，并通过exit函数确保主循环安全结束
    sys.exit(app.exec_())
